<template>
  <PlusPage
    ref="plusPageInstance"
    :columns="pageConfig"
    :table="{
      adaptive: true,
      hasIndexColumn: true,
      actionBar: { buttons, width: 180 },
    }"
    :default-page-info="{ pageSize: DEFAULT_PAGE_SIZE, page: 1 }"
    :request="getList"
  >
    <template #table-title>
      <el-row class="button-row">
        <el-button type="primary" :icon="Plus" @click="handleCreate">新增</el-button>
      </el-row>
    </template>
  </PlusPage>

  <!-- 弹窗新增or编辑 -->
  <PlusDialogForm
    v-model:visible="pageState.formVisible"
    v-model="pageState.form"
    :form="{ columns: pageConfig, rules: pageState.rules, labelWidth: 100 }"
    :dialog="{
      title: dialogTitle + '用户',
      width: '540px',
      top: '12vh',
      confirmLoading: pageState.confirmLoading,
    }"
    @confirm="handleSubmit"
    @cancel="handleCancel"
    @close="handleCancel"
  />
</template>

<script lang="ts" setup>
import type { ButtonsCallBackParams, PlusColumn, PlusPageInstance } from '@wlydfe/pro-ui'
import type { BasePageReq } from '@wlydfe/service'
import { Plus } from '@element-plus/icons-vue'
import { REGEX } from '@wlydfe/core'
import { useTable } from '@wlydfe/pro-ui'
import { ElMessage } from 'element-plus'
import { assign, omit } from 'lodash-es'
import { ref } from 'vue'
import { systemApi } from '@/api'

//#region  -----------数据源-----------

const defaultForm = {
  enableFlag: '1',
  loginName: '',
  password: '',
  operatorName: '',
  telephone: '',
  email: '',
  roleName: '',
  remark: '',
  permissionInfoIds: [],
}

const plusPageInstance = ref<PlusPageInstance | null>(null)

const pageState = ref({
  formVisible: false, // 新增or编辑的弹窗是否显示
  isCreate: true, // 是否是新增
  confirmLoading: false,
  form: { ...defaultForm },
  rules: {
    loginName: [
      {
        required: true,
        message: '请输入账号',
        trigger: 'blur',
      },
      {
        max: 10,
        min: 6,
        message: '请输入6~10之间的字符',
        trigger: 'blur',
      },
    ],
    operatorName: [
      {
        required: true,
        message: '请输入用户姓名',
        trigger: 'blur',
      },
    ],
    password: [
      {
        required: true,
        message: '请输入密码',
        trigger: 'blur',
      },
    ],
  },
})

const dialogTitle = computed(() => (pageState.value.isCreate ? '新增' : '编辑'))

const roleOptions = ref<any[]>([])

const getRoleOptions = async () => {
  const { succeed, model } = await systemApi.getRolePage({
    currentPage: 1,
    pageLength: 1000,
    filterModel: {
      sysType: '31',
    },
  })
  if (succeed) {
    roleOptions.value = model.map((item: any) => ({
      label: item.name,
      value: item.roleId,
    }))
  }
}
getRoleOptions()
//#endregion

//#region  -----------页面配置-----------

const pageConfig: PlusColumn[] = [
  {
    label: '账号',
    prop: 'loginName',
    hideInSearch: false,
    fieldProps: {
      disabled: !pageState.value.isCreate,
      maxlength: 10,
    },
  },
  {
    label: '初始密码',
    prop: 'password',
    hideInSearch: true,
    hideInTable: true,
    fieldProps: {
      disabled: !pageState.value.isCreate,
      maxlength: 16,
    },
  },
  {
    label: '姓名',
    prop: 'operatorName',
    hideInSearch: false,
  },
  {
    label: '手机号',
    prop: 'telephone',
    hideInSearch: false,
    fieldProps: {
      maxlength: 11,
      number: true,
    },
  },
  {
    label: '邮箱',
    prop: 'email',
    fieldProps: {
      maxlength: 50,
    },
  },
  {
    label: '角色',
    prop: 'roleName',
    hideInSearch: false,
    hideInForm: true,
  },
  {
    label: '角色',
    prop: 'permissionInfoIds',
    hideInSearch: true,
    hideInTable: true,
    valueType: 'select',
    options: computed(() => roleOptions.value),
    fieldProps: {
      filterable: true,
      multiple: true,
      clearable: true,
    },
  },
  {
    label: '状态',
    prop: 'enableFlag',
    valueType: 'select',
    hideInForm: true,
    options: [
      {
        label: '停用',
        value: '0',
      },
      {
        label: '启用',
        value: '1',
      },
    ],
  },
  {
    label: '创建人',
    prop: 'creatorName',
    hideInForm: true,
  },
  {
    label: '创建时间',
    prop: 'createdDate',
    width: 180,
    hideInForm: true,
  },
  {
    label: '描述',
    prop: 'remark',
    hideInSearch: true,
    hideInTable: true,
    valueType: 'textarea',
    fieldProps: {
      maxlength: 200,
    },
  },
  {
    label: '是否开启',
    prop: 'enableFlag',
    hideInSearch: true,
    hideInTable: true,
    valueType: 'switch',
    fieldProps: {
      activeValue: '1',
      inactiveValue: '0',
    },
  },
]

//#endregion

//#region  -----------操作按钮-----------

const { buttons } = useTable()
buttons.value = [
  {
    text: '修改',
    code: 'update',
    props: { type: 'primary' },
    onClick: async (params: ButtonsCallBackParams) => {
      const id = params.row.id
      const { succeed, model } = await systemApi.getUserInfoById(id)
      if (succeed) {
        pageState.value.form = { ...model, userId: id } as any
        pageState.value.form.permissionInfoIds =
          model.permissionInfoIds?.map((item: any) => item.roleId) || []
        pageState.value.form.password = '******'
        pageState.value.isCreate = false
        pageState.value.formVisible = true
      }
    },
  },
  {
    text: '停用',
    code: 'stop',
    show: row => row.enableFlag === '1',
    props: { type: 'primary' },
    confirm: {
      title: '提示',
      message: '确定停用该账号吗？',
      options: {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      },
    },
    onConfirm: async (params: ButtonsCallBackParams) => {
      params.row.enableFlag = '0'
      await systemApi.suspensionUserInfo(params.row.id)
      ElMessage.success('停用成功')
      refreshPage()
    },
  },
  {
    text: '启用',
    code: 'start',
    show: row => row.enableFlag === '0',
    props: { type: 'primary' },
    confirm: {
      title: '提示',
      message: '确定启用该账号吗？',
      options: {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      },
    },
    onConfirm: async (params: ButtonsCallBackParams) => {
      params.row.enableFlag = '1'
      await systemApi.activationUserInfo(params.row.id)
      ElMessage.success('启用成功')
      refreshPage()
    },
  },
  {
    text: '删除',
    code: 'delete',
    props: { type: 'primary' },
    confirm: {
      title: '提示',
      message: '确定删除该账号吗？',
      options: {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      },
    },
    onConfirm: async (params: ButtonsCallBackParams) => {
      await systemApi.deleteUser(params.row.id)
      ElMessage.success('删除成功')
      refreshPage()
    },
  },
]

// 创建
const handleCreate = (): void => {
  pageState.value.form = { ...defaultForm }
  pageState.value.isCreate = true
  pageState.value.formVisible = true
}

// 提交表单成功
const handleSubmit = async () => {
  const params = { ...pageState.value.form, sysType: '31' }
  console.log('----from-----', params)
  if (pageState.value.isCreate) {
    if (!REGEX.numberAndCodeRule.test(params.password)) {
      ElMessage.info('请输入6~16位字母、数字和英文符号组合的密码！')
      return
    }
  } else {
    // 编辑状态下
    Reflect.deleteProperty(params, 'password')
  }

  if (params.email && !REGEX.emailRule.test(params.email)) {
    ElMessage.info('请输入正确的邮箱！')
    return
  }

  if (params.telephone && !REGEX.phoneRule.test(params.telephone)) {
    ElMessage.info('请输入正确的手机号！')
    return
  }

  pageState.value.confirmLoading = true
  const { succeed } = await systemApi.addOrEditUser(pageState.value.isCreate, params)
  pageState.value.confirmLoading = false
  if (succeed) {
    ElMessage.success(pageState.value.isCreate ? '创建成功' : '更新成功')
    handleCancel()
    refreshPage()
  }
}

// 表单取消
const handleCancel = () => {
  pageState.value.formVisible = false
  pageState.value.isCreate = true
}

// 刷新表格
const refreshPage = () => {
  plusPageInstance.value?.getList()
}
//#endregion

//#region  -----------接口请求及参数-----------

const DEFAULT_PAGE_SIZE = 20
const queryParams = ref<BasePageReq<Record<string, any>>>({
  currentPage: 1,
  pageLength: DEFAULT_PAGE_SIZE,
  countTotal: true,
  filterModel: {
    sysType: '31',
  },
})

const getList = async (query: Record<string, any>) => {
  // 构造查询参数
  queryParams.value.currentPage = query.page ?? 1
  queryParams.value.pageLength = query.pageSize ?? DEFAULT_PAGE_SIZE
  queryParams.value.filterModel = assign(
    queryParams.value.filterModel,
    omit(query, ['page', 'pageSize', 'value']),
  )

  const { succeed, model, total } = await systemApi.getUserPage(queryParams.value)
  return {
    data: succeed ? model : [],
    total: total ?? 0,
  }
}
//#endregion
</script>
